//
//  OAuthViewController.swift
//  sinaweiboFirst
//
//  Created by mac on 16/3/7.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close() {

        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func defaultAction() {
        
        //需要在webView中设置帐号和密码
        let javaScript = "document.getElementById('userId').value = '18627072847', document.getElementById('passwd').value = 'dgy906369286' "
        
        //通过字符串来执行javascript代码
        webView.stringByEvaluatingJavaScriptFromString(javaScript)
    }
    
    override func loadView() {
        view = webView
        
        //解决黑条问题
        webView.opaque = false
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置导航栏
        setNavgationBar()
        //手动创建的视图控制器 根视图的背景色是透明的
        view.backgroundColor = UIColor.whiteColor()
        
        //加载授权页面
        loadOAuthPage()
    }
    
    //view消失 网络圈圈也消失
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    //加载授权页面
    private func loadOAuthPage() {
    
        //1.urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        //2.NSURL
        let url = NSURL(string: urlString)
        //3.NSURLRequest
        let request = NSURLRequest(URL: url!)
        //
        webView.loadRequest(request)
    }

    private func setNavgationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "defaultAction")
    
    }
}

//***************扩展方法: webView协议方法**********************
extension OAuthViewController: UIWebViewDelegate {

    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
//***********一般协议方法 返回值为bool类型 默认返回yes 对应控件能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //包含了回调地址的url中 一定包含了code字段
        if urlString.containsString("code") {
            //不加载网页
            
            //在这里需要获取URL中包好的code 使用code获取token
            guard  let query = request.URL?.query else {
                return false
            }
            
            let codeStr = "code="
            //将String转换成NSString
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            // 使用code来获取token
//            loadAccesToken(code) 
            UserAccount.shareAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus(appNetTip)
                    return
                }
                
                //登录成功 销毁当前页面
//                self.close()
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    // 通知是同步的
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: "oauth")
                    
                    print("如果通知是异步的,先走这里")
                })
            })
            return false
        }
        return true
    }
}
